<template>
  <div class="app-container">
    <div class="header">
        <span style="width: 100px;">数据类别：</span>
        <el-space wrap :size="20" style="flex: 1;">
          <template v-for="item,index in optionDataType" :key="index">
            <span @click="chickHandle(item,index)" :class="[{active:index === current},'spanStyles']">{{ item.dictItemName }}</span>
          </template>
        </el-space>
        <div style="display: flex;align-items: flex-end;color: #107ce5;">
          <span v-if="isSearch" @click="isSearch=false">高级检索</span>
          <span v-else @click="isSearch=true">初级检索</span>
        </div>
    </div>
  <div v-if="isSearch" class="queryForm">
    <el-input v-model="queryParams.keyword" placeholder="请输入关键字" style="width: 700px;">
      <template #append><el-button class="btn" @click="handleQuery">搜索</el-button></template>
    </el-input>
  </div>
  <div v-else style="padding: 20px 30px 0px 30px;background-color: #f5f9fe;margin: 10px 0px;">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px">
      <el-form-item label="版本日期">
        <el-form-item label-width="0px">
          <el-date-picker style="width:140px" v-model="queryParams.versionStartTime" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisabledDate"/>
        </el-form-item>
        <span class="spanStyle">至</span> 
        <el-form-item>
          <el-date-picker style="width:140px"  v-model="queryParams.versionEndTime" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" :disabled-date="endDisabledDate"/>
        </el-form-item>
      </el-form-item>
      <el-form-item label="上传日期">
        <el-form-item label-width="0px">
          <el-date-picker style="width:140px" v-model="queryParams.uploadStartTime" type="date" placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisabledDate1"/>
        </el-form-item>
        <span class="spanStyle">至</span> 
        <el-form-item>
          <el-date-picker style="width:140px"  v-model="queryParams.uploadEndTime" type="date" placeholder="结束时间" value-format="YYYY-MM-DD" :disabled-date="endDisabledDate1"/>
        </el-form-item>
      </el-form-item>
      <el-form-item label="版本号" prop="versionCode">
        <el-input style="width:300px" v-model="queryParams.versionCode" placeholder="请输入版本号" clearable />
      </el-form-item>
      <el-form-item label="数据名称" prop="dataName">
        <el-input  style="width:300px" v-model="queryParams.dataName" placeholder="请输入数据名称" clearable />
      </el-form-item>
      <el-form-item label="数据类别" prop="dataType">
        <el-select v-model="queryParams.dataType" placeholder="请选择" clearable @change="chooseType"
          style="width:130px;margin-right:40px">
          <el-option v-for="item in optionData" :key="item.dictItemId" :label="item.dictItemName"
            :value="item.dictItemId">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataType2" placeholder="请选择" clearable style="width:130px;">
          <el-option v-for="item in optionData2" :key="item.dictItemId" :label="item.dictItemName"
            :value="item.dictItemId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据范围">
        <el-select v-model="queryParams.dataRangeCountry" placeholder="请选择" @change="chooseScope"
          style="width:130px;margin-right:10px" clearable>
          <el-option v-for="item in [{ value: 1, label: '国家级' }, { value: 2, label: '省级' }]" :key="item.value"
            :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataRangeProvince" placeholder="省" style="width:130px;margin-right:10px"
          @change="chooseProvince" clearable>
          <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataRangeCity" placeholder="市" style="width:130px;margin-right:10px"
          @change="chooseCity" clearable>
          <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
        <el-select v-model="queryParams.dataRangeArea" placeholder="区县" style="width:130px;" clearable>
          <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 40px;">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
  </div>

  <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="Edit" :disabled="multiple" @click="handleExport">导出</el-button>
      </el-col>
      <div class="top-right-btn">
        <el-button style="color:#107ce5;cursor: pointer;" @click="toView">数据视图</el-button>
      </div>
    </el-row>

    <el-table v-loading="loading" ref="tableRef" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="id">
      <el-table-column type="expand" width="1">
        <template #default="props">
          <div class="expandTable">
            <h3>更多信息</h3>
            <p>版本说明: {{ props.row.versionDesc }}（此处是版本说明，<span style="color:red">限制300字以内</span> ）</p>
            <p>数据说明: {{ props.row.dataDesc }}（此处是数据说明，<span style="color:red">限制300字以内</span> ）</p>
            <p v-if="props.row.updateDesc">更新说明: {{ props.row.dataType }}</p>
            <!-- <p>使用系统: {{ props.row.useThisSystems }}
              <el-tooltip class="box-item" content="Right Center prompts info" placement="right">
                <el-tag>系统使用说明</el-tag>
              </el-tooltip>
            </p> -->
            <p>数据文件:
              <template v-for="item in props.row.dataFileList">
                <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name }}</u><br />
              </template>
            </p>
            <p>附件:
              <template v-for="item in props.row.attachmentList">
                <u style="color:#107ce5;cursor: pointer;" @click="handleDownload(item)">{{ item.name }}</u><br />
              </template>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="版本日期" align="center" prop="versionTime" />
      <el-table-column label="版本号" align="center" prop="versionCode" />
      <el-table-column label="数据名称" align="center" prop="dataName" />
      <el-table-column label="数据类别" align="center" prop="dataType" />
      <el-table-column label="数据范围" align="center" prop="dataRange" />
      <el-table-column label="上传日期" align="center" prop="uploadTime" />
      <el-table-column label="上传人" align="center" prop="uploadUser" />
      <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" @click="handleMore(scope.row)">更多数据</el-button>
          <el-button type="text" @click="openDetail(scope.row.versionCode)">元数据管理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

          <!-- 元数据信息 -->
    <el-dialog v-model="openData" width="800px" title="元数据信息" append-to-body>
      <el-form ref="ruleFormData" :model="formData" label-width="120px">
        <p class="mt15"></p>
        <el-form-item label="上传人">{{ formData.uploadUser }}</el-form-item>
        <el-form-item label="上传日期">{{ formData.uploadTime }}</el-form-item>
        <el-form-item label="数据来源" prop="uploadSource">
          <el-input v-model="formData.uploadSource" placeholder="数据提供的部门、单位名称、下载的途径、来源网站等" clearable disabled />
        </el-form-item>
        <el-form-item label="数据类别" prop="type">{{ formData.dataType }}</el-form-item>
        <el-form-item label="数据范围" prop="dataScope">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item prop="dataRangeCountry" label-width="0px">
                <el-select v-model="formData.dataRangeCountry" placeholder="请选择" style="width:100%" disabled>
                  <el-option v-for="item in [{ value: 1, label: '国家级' }, { value: 2, label: '省级' }]" :key="item.value"
                    :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item prop="dataRangeProvince" label-width="0px">
                <el-select v-model="formData.dataRangeProvince" placeholder="省" style="width:100%" disabled>
                  <el-option label="全国" :value="null"></el-option>
                  <el-option v-for="item in provinceFormData1" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.dataRangeCity" placeholder="市" style="width:100%" disabled>
                <el-option label="全部" :value="null"></el-option>
                <el-option v-for="item in cityFormData1" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.dataRangeArea" placeholder="区县" style="width:100%" disabled>
                <el-option label="全部" :value="null"></el-option>
                <el-option v-for="item in areaFormData1" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="是否空间数据">
          <el-radio-group v-model="formData.isSpatialData" disabled>
            <el-radio :label="1">空间数据</el-radio>
            <el-radio :label="0">非空间数据</el-radio>
          </el-radio-group>
        </el-form-item>

        <template v-if="formData.isSpatialData == '1'">
          <el-form-item label="空间数据类型" prop="spatialDataType">
            <el-radio-group v-model="formData.spatialDataType" disabled>
              <el-radio :label="1">点</el-radio>
              <el-radio :label="2">线</el-radio>
              <el-radio :label="3">面</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="tab-title">基于坐标的空间参照系</div>
          <el-form-item label="坐标系类型">{{ formData.coordinateSystemType }}</el-form-item>
          <el-form-item label="坐标系名称">{{ formData.coordinateSystemName }}</el-form-item>
          <el-form-item label="英文缩写">{{ formData.coordinateSystemEnName }}</el-form-item>
          <!-- <el-form-item label="投影信息" prop="projectionInfo">
            <el-input v-model="formData.projectionInfo" placeholder="请输入投影信息" clearable disabled/>
          </el-form-item> -->
        </template>
        <div class="tab-title">数据字段</div>
        <el-form-item label="字段个数" prop="fieldNum">
          <el-input v-model="formData.fieldNum" placeholder="请输入字段个数" clearable disabled/>
        </el-form-item>
        <el-form-item label="字段条目" prop="fieldEntry">
          <el-input v-model="formData.fieldEntry" placeholder="请输入字段条目" clearable disabled/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="openData = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
</div>
</template>

<script setup>
import { ElMessageBox } from 'element-plus'
import { getProvince, getChildArea } from "@/api/system/division";
import { list, listAll, getDataTye, getDataTyes, getChildDataType, getDetail } from '@/api/integratedSearch.js'
const { proxy } = getCurrentInstance();
const router = useRouter();
const isSearch = ref(true);
const loading  = ref(false);
const total  = ref(0);
const ids = ref(true);
const single = ref(true);
const multiple = ref(true);
const optionDataType = ref([]);
const dataList = ref([]);
const optionData = ref([]);
const optionData2 = ref([]);
const provinceData = ref([]);//省
const cityData = ref([]);//市
const areaData = ref([]); //区、县
const provinceFormData1 = ref([]);//省
const cityFormData1 = ref([]);//市
const areaFormData1 = ref([]); //区、县
const current = ref(0);
const openData = ref(false);
const selectData = ref([]);

const data = reactive({
  queryParams: {
    dataTypeCode: '',
    keyword:'',
    page: 1,
    rows: 10,
    versionCode: '',
    dataName: '',
    dataType: '',
    dataType2: '',
    dataRangeCountry: '',
    dataRangeProvince: '',
    dataRangeCity: '',
    dataRangeArea:'',
    versionStartTime: '',
    versionEndTime: '',
    uploadStartTime: '',
    uploadEndTime: '',
  },
  formData: {},
})
const { queryParams, formData } = toRefs(data);

const startDisabledDate = (time) => {
  if (queryParams.value.versionEndTime) {
    return time.getTime() > new Date(queryParams.value.versionEndTime).getTime();
  }
  return false;
};
const endDisabledDate = (time) => {
  if (queryParams.value.versionStartTime) {
    return time.getTime() < new Date(queryParams.value.versionStartTime).getTime();
  }
  return false;
};

// 监听开始时间和结束时间的变化，更新对应的 disabledDate 函数
watch(queryParams.value.versionStartTime, (newVal) => {
  // 当开始时间改变时，更新结束时间的选择范围
  endDisabledDate(newVal);
});

watch(queryParams.value.versionEndTime, (newVal) => {
  // 当结束时间改变时，更新开始时间的选择范围
  startDisabledDate(newVal);
});

const startDisabledDate1 = (time) => {
  if (queryParams.value.uploadEndTime) {
    return time.getTime() > new Date(queryParams.value.uploadEndTime).getTime();
  }
  return false;
};
const endDisabledDate1 = (time) => {
  if (queryParams.value.uploadStartTime) {
    return time.getTime() < new Date(queryParams.value.uploadStartTime).getTime();
  }
  return false;
};
// 监听开始时间和结束时间的变化，更新对应的 disabledDate 函数
watch(queryParams.value.uploadStartTime, (newVal) => {
  // 当开始时间改变时，更新结束时间的选择范围
  endDisabledDate1(newVal);
});

watch(queryParams.value.uploadEndTime, (newVal) => {
  // 当结束时间改变时，更新开始时间的选择范围
  startDisabledDate1(newVal);
});

watch(isSearch, (value) => {
  if(value){
    queryParams.value.page = 1;
    queryParams.value.rows = 10;
    queryParams.value.versionCode = '';
    queryParams.value.dataName = '';
    queryParams.value.dataType = '';
    queryParams.value.dataType2 = '';
    queryParams.value.dataRangeCountry = '';
    queryParams.value.dataRangeProvince = '';
    queryParams.value.dataRangeCity = '';
    queryParams.value.dataRangeArea = '';
    queryParams.value.versionStartTime = '';
    queryParams.value.versionEndTime = '';
    queryParams.value.uploadStartTime = '';
    queryParams.value.uploadEndTime = '';
  }else{
    queryParams.value.page = 1;
    queryParams.value.rows = 10;
    queryParams.value.keyword = '';
  }
})



// 下载文件
function handleDownload(row) {
  var query = {
    attachId: row.id,
    name: row.name
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}
// 打开元信息
function openDetail(versionCode) {
  handleDetail(versionCode)
}
// 数据详情
function handleDetail(versionCode) {
  getDetail(versionCode).then(res => {
    formData.value = res.data;
    editProvinceFormData(formData.value.dataRangeProvince, formData.value.dataRangeCity)
  })
}

// 去数据视图
function toView() {
  const flag = ids.value.length == 1
  if (flag) {
    router.push({
      path: '/essentialData/dataView',
      query: {
        versionCode: selectData.value[0].versionCode,
        typeCode:selectData.value[0].dataTypeLevel3Code
      }
    })
  } else {
    ElMessageBox.alert('请勾选一条版本数据进行查看。', '消息提示', {
      confirmButtonText: '确认',
      type: 'warning'
    })
  }
}

// 更多数据
function handleMore(row) {
  proxy.$refs['tableRef'].toggleRowExpansion(row);
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectData.value = selection;
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('/datacenter/sysDataVersion/dataExport', ids.value, `文件${new Date().getTime()}.xls`)
}

// 高亮
function chickHandle(item,index){
  current.value = index;
  queryParams.value.dataTypeCode = item.dictItemCode;
  queryParams.value.dataType = '';
  queryParams.value.dataType2 = '';
  if(queryParams.value.dataTypeCode==''){
    optionData.value = [];
    optionData2.value = [];
    getAllDataType();
  }else{
    getDataTyes(queryParams.value.dataTypeCode).then(res => {
      optionData.value = res.data;
  })
  }
  handleQuery();
}
function chooseScope(value) {
  queryParams.value.dataRangeProvince = null;
  queryParams.value.dataRangeCity = null;
  queryParams.value.dataRangeArea = null;
}
// 获取一级数据类别
function dataTye(){
  getDataTye().then(res=>{
    // console.log(res.data,'一级数据');
    optionDataType.value =[{dictItemName:'全部',dictItemCode:''}, ...res.data];
  })
}
// 获取所有的二级数据类别
function getAllDataType(){
  listAll().then(res=>{
    optionData.value =res.data;
  })
}
// 获取三级数据类别
function chooseType(value) {
  queryParams.value.dataType2 = '';
  if (value == '') {
    optionData2.value = [];
  } else {
    optionData.value.forEach(item => {
      if (value == item.dictItemId) {
        getChildDataType(item.dictItemCode).then(res => {
          optionData2.value = res.data;
        })
      }
    })
  }
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    dataTypeCode: '',
    page: 1,
    rows: 10,
    versionCode: '',
    dataName: '',
    dataType: '',
    dataType2: '',
    dataRangeCountry: '',
    dataRangeProvince: '',
    dataRangeCity: '',
    dataRangeArea: '',
    versionStartTime: '',
    versionEndTime: '',
    uploadStartTime: '',
    uploadEndTime: '',
  },
    dataList.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 获取省列表 */
function getProvinceData() {
  getProvince().then(response => {
    provinceData.value = response.data;
    provinceFormData1.value = response.data;
  });
}
function chooseProvince(value) {
  queryParams.value.dataRangeCity = null;
  queryParams.value.dataRangeArea = null;
  cityData.value = [];
  getChildArea(value).then(response => {
    cityData.value = response.data;
  });
}
function chooseCity(value) {
  queryParams.value.dataRangeArea = null;
  areaData.value = [];
  getChildArea(value).then((response) => {
    areaData.value = response.data;
  });
}
function editProvinceFormData(provinceId, cityId) {
  if (!provinceId && !cityId) {
    cityFormData1.value = [];
    areaFormData1.value = [];
  }
  if (provinceId && !cityId) {
    getChildArea(provinceId).then(response => {
      cityFormData1.value = response.data;
      areaFormData1.value = [];
    });
  }
  if (provinceId && cityId) {
    getChildArea(provinceId).then(response => {
      cityFormData1.value = response.data;
    });
    getChildArea(cityId).then(response => {
      areaFormData1.value = response.data;
    });
  }
  openData.value = true;
  proxy.resetForm("ruleFormData");
  formData.value.dataRange = '1';
}
/** 查询数据列表 */
function getList() {
  loading.value = true;
  list({...queryParams.value}).then(response => {
    dataList.value = response.data.list ? response.data.list : [];
    total.value = response.data.total;
    loading.value = false;
    // getVersionCodes();
  });
  if(queryParams.value.dataTypeCode==''){
    getAllDataType();
  }
}

getList();
dataTye();
getProvinceData();
</script>

<style lang="scss" scoped>
.header{
  display: flex;
  justify-content: space-between;
  color: #333333;
  span{
    height: 30px;
    line-height: 30px;
    display: inline-block;
  }
  .spanStyles{
    padding:0px 10px;
    height: 30px;
    line-height: 30px;
    border-radius: 4px;
    cursor: pointer;
  }
  .active{
        color: #107ce5;
        background-color: #c6e2ff;
        cursor: pointer;
    }
}
.queryForm{
  background-color: #f5f9fe;
  padding: 20px 30px;
  width: 100%;
  text-align: center;
  margin: 10px 0px;
  .el-input-group__append{
    background-color: #107ce5!important;
    color: #fff!important;
  }
  .btn{
    background-color: #107ce5!important;
    color: #fff!important;
    border-radius: 0px!important;
  }
}

.expandTable {
  padding: 5px 20px 5px 105px;

  h3 {
    font-weight: bold;
  }

  p {
    margin: 0px;
    line-height: 25px !important;
  }
}

.tab-title {
  font-size: 16px;
  font-weight: bold;
  border-left: 4px solid #0D9AFF;
  font-family: PingFangSC-Medium;
  padding-left: 10px;
  margin-bottom: 20px;
}

:deep(.el-drawer__header) {
  margin-bottom: 0px !important;
}

.el-form--inline .el-form-item{
  margin-right: 0px!important;
}
.spanStyle{
  display: inline-block;
  width: 20px;
  text-align: center;
}
:deep(.el-table__expand-icon){
  display: none;
}
</style>
